//
//  FWTabBarView.m
//  SinaWebo
//
//  Created by wwj on 16/2/16.
//  Copyright © 2016年 亦心. All rights reserved.
//

#import "FWTabBarView.h"
#define kFWMargin 60
#define kFWBtnWith 85


@interface FWTabBarView ()
@property (copy, nonatomic) NSArray *dataArray;
@property (weak, nonatomic) UIView *buttomView;
@property (weak, nonatomic) UIButton *selectBtn;
@end

@implementation FWTabBarView

-(NSArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = @[@"主页", @"微博", @"相册"];
    }
    return _dataArray;
}

- (instancetype)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {
        [self initView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}


- (void)initView{
    
    UIView *buttomView = [[UIView alloc] init];
    buttomView.backgroundColor = [UIColor orangeColor];
    CGRect frame = buttomView.frame;
    frame.size = CGSizeMake(kFWBtnWith-20, 2);
    buttomView.frame = frame;
    [self addSubview:buttomView];
    _buttomView = buttomView;
    
    [self setUpButton];
   
}

- (void)setUpButton{
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    CGFloat margin = kScreenW - 2 * kFWMargin - (self.dataArray.count) * kFWBtnWith;
    for (int index = 0; index < _dataArray.count; index++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:_dataArray[index] forState:UIControlStateNormal];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(onSelectBtn:) forControlEvents:UIControlEventTouchDown];
        button.tag = index;
        CGFloat btnX = kFWMargin + (kFWBtnWith + margin) * (index % _dataArray.count);
        button.frame = CGRectMake(btnX, 0, kFWBtnWith, 42);
        [self addSubview:button];
        
        if (index == 0) {
            _buttomView.center = CGPointMake(button.center.x, 42);
            [self onSelectBtn:button];
        }
    }
}

- (void)onSelectBtn:(UIButton *)button{
    if (_selectBtn == button) return;
    
    if ([_delegate respondsToSelector:@selector(onClickTabBar:from:to:)]) {
        [_delegate onClickTabBar:self from:_selectBtn.tag to:button.tag];
    }
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    [UIView animateWithDuration:0.3 animations:^{
         _buttomView.center = CGPointMake(button.center.x, 42);
    }];
}

@end
